import React, {useState, useEffect, useMemo} from 'react';
import { InfoDlg, uJob, cline, Btn, is_empty, obj_str, loc, PanelFind, Ret, Title, filter_row, useCmd, useHigh, d_sort, GridTable } from 'sui';

const PsnView = ({ cur, hreturn, title, mod }) => {
    const [info, setInfo] = useState(false);
    const [row, setRow] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        if (!cur) {
            setRow(null);
            return;
        }

        const tmp = cur.v;
        if (is_empty(tmp)) {
            setRow(null);
            return;
        }

        if (mod === "pair") {
            d_sort(tmp, "groupsn");
        } else {
            d_sort(tmp, "sn");
        }
        tmp.forEach((d, i) => d["index"] = i + 1);

        setRow(tmp);
    }, [cur, mod]);

    const getCol = useMemo(() => {
        const col = [
            {name: loc("l_193"), key: 'index', width: 70},
            {name: loc("l_152"), key: 'sn', width: 100},
            {name: loc("l_751"), key: 'groupsn', width: 100},
            {name: loc("l_229"), key: 'gtp', width: 70},
            {name: loc("l_315"), key: 'task', width: 130},
            {name: loc("l_745"), key: 'outdia', width: 100},
            {name: loc("l_746"), key: 'india', width: 100},
            {name: loc("l_747"), key: 'outwidth', width: 100},
            {name: loc("l_748"), key: 'standout', width: 100},
        ];

        if (mod === "any") {
            return col.filter(d => {
                const k = d.key;
                return k !== "groupsn" && k !== "gtp";
            });
        }

        return col;
    }, [mod]);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(row, lst, umd.filter);
    }, [row, umd.filter]);

    const htask = () => {
        if (is_empty(row)) {
            return;
        }

        umd.startWait();

        const tmp = row.map(d => d.sn);

        uJob(null, "pair/task",
            {
                line: cline(),
                k: mod,
                tech: obj_str(cur, "sn"),
                v: tmp,
            },
            r => {
                umd.endWait();
                alert(loc("l_825"));
            }
            , e => umd.setErr(), true);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => setInfo(true)}>{loc("l_706")}</Btn>
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Title mod={obj_str(cur, "sn")} sub={title}/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol} row={getRow}/>
            <InfoDlg open={info} setOpen={setInfo} msg={loc("l_826")} hcmd={htask} hcancel={() => setInfo(false)}/>
        </div>
    );
};

export {PsnView};
